#include"pipe.hpp"
using work_t = std::function<void()>;
class chh
{
public:
    chh(int num, work_t w):_num(num), work(w)
    {

    }
    

    //创建子进程
    void add()
    {
        for(int i=0;i<_num;i++)
        {
            int fds[2];
            int n = pipe(fds);
            if(n < 0)
            {
                perror("pipe");
                exit(1);
            }
            pid_t id = fork();
            if(id < 0)
            {
                perror("fork");
                exit(2);
            }
            else if(id == 0)
            {
                //子进程
                ::close(fds[1]);
                ::dup2(fds[0],0);
                //执行任务的方法-多进程执行一个方法传一个过来就行了
                test_wrk();
                exit(0);
            }
            //父进程
            ::close(fds[0]);

            fs.emplace_back(fds[1],id);
            
        }
    }
    void printf_name()
    {
        for(auto& i:fs)
        {
            std::cout << i.Name() << std::endl;
        }
    }
    //派发任务
    void atch()
    {
        int num = 0;
        int c=10;
        while(c)
        {
            int task = tm.text_rand();
            //选择一个目标进程
            pipe_test& tt = fs[num++];
            num %= fs.size();
            std::cout << "######################" << std::endl;
            std::cout <<"已派发任务" << "目标进程pid:" << tt.Pid() << std::endl;
            std::cout << "######################" << std::endl;

            //派发任务
            tt.Write(task);
            c--;
            sleep(1);
        }
    }
    void cle()
    {
        //关闭所有子进程
        for(auto &i:fs)
        {
            i.Close();
        }
        for(auto& i:fs)
        {
            pid_t rid = write(i.Pid(),nullptr,0);
            if(rid > 0)
            {
                std::cout << "rid:" << rid << "已回收" << std::endl;
            }
        }
    }

private:
    int _num;
    std::vector<pipe_test> fs;
    work_t work;
};